<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-row>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="设备标识" prop="devices" label-position="right">
            <el-input
                v-model="queryParams.devices"
                placeholder="设备标识"
                @keyup.enter="handleQuery"
                :clearable="true"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6" v-if="false">
            <el-form-item label="号码类型" prop="sim" label-position="right">
              <el-select v-model="queryParams.sim" placeholder="请选择" style="width: 200px" :clearable="true">
                <el-option label="首次" value="fst" />
                <el-option label="二次" value="sec" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="国家" prop="country" label-position="right">
                <el-select v-model="queryParams.country" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option v-for="item in countriesList" :key="item.code" :label="item.name" :value="item.code">
                    <span class="flag-icon" :class="`flag-icon-${item.code.toLowerCase()}`"></span>
                    <span style="margin-left: 5px;">{{ item.name }}</span>
                  </el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6" v-if="false">
            <el-form-item label="批次" prop="keywords" label-position="right">
              <el-input
                :clearable="true"
                v-model="queryParams.keywords"
                placeholder="请输入"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="手机号" prop="mobile" label-position="right">
              <el-input
                :clearable="true"
                v-model="queryParams.mobile"
                placeholder="请输入"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>

          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="起止时间" prop="createdAt" label-position="right">
              <el-date-picker
                style="width: 300px;"
                v-model="queryParams.times"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="导出状态" prop="exported" label-position="right">
              <el-select v-model="queryParams.exported" placeholder="请选择" style="width: 200px" :clearable="true">
                <el-option label="未导出" value="no"></el-option>
                <el-option label="已导出" value="yes"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6" v-if="false">
            <el-form-item label="封禁状态" prop="status" label-position="right">
              <el-select v-model="queryParams.status" placeholder="请选择" style="width: 200px" :clearable="true">
                <el-option label="未封禁" value="normal"></el-option>
                <el-option label="封禁" value="banned"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-dropdown @command="handleClickBatch($event, 'Rows', {})">
        <el-button type="primary" style="margin-bottom: 10px;">
          批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="export">导出</el-dropdown-item>
            <el-dropdown-item command="delete">删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="手机号" prop="mobile" min-width="150">
          <template #default="scope">
            <span>{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="App" prop="app" min-width="60">
          <template #default="scope">
            <span>{{ scope.row.app }}</span>
          </template>
        </el-table-column>
        <el-table-column label="设备标识" prop="device"  min-width="100">
          <template #default="scope">
            <span>{{ scope.row.device }}</span>
          </template>
        </el-table-column>
        <el-table-column label="号码类型" prop="sim" min-width="100" v-if="false">
          <template #default="scope">
            {{ {
              'unknown': '--',
              '1': '首次',
              '2': '非首次',
            }[scope.row.sim] }}
          </template>
        </el-table-column>
        <el-table-column label="国家" prop="countryCode">
          <template #default="{ row }">
            <span class="flag-icon" :class="`flag-icon-${row.countryCode.toLowerCase()}`"></span>
            <span style="margin-left: 5px;">{{ row.countryName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="封禁状态" prop="status" min-width="100" v-if="false">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.status == 'normal'">正常</el-tag>
            <el-tag type="danger" v-if="scope.row.status == 'banned'">封禁</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" min-width="160">
          <template #default="scope">
            {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : '--'}}
          </template>
        </el-table-column>
        <el-table-column label="导出时间" prop="updatedAt" min-width="160">
          <template #default="scope">
            {{ scope.row.exportedAt ? formatDate(scope.row.exportedAt) : '--'}}
          </template>
        </el-table-column>
        <el-table-column label="是否导出" prop="exported" min-width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.exported === 'yes'">已导出</el-tag>
            <el-tag type="info" v-else>未导出</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">

            <el-dropdown @command="handleClickBatch($event, 'Row', scope.row)">
              <span class="el-dropdown-link">
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="paging.page"
          v-model:page-size="paging.size"
          :page-sizes="['10', '20', '30', '50', '100']"
          :size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <ExportRows ref="exportRowsRef" />
  </div>
</template>

<script setup>
import { saveAs } from 'file-saver';
import ExportRows from "./exportRows.vue";
import { formatDate } from "@/utils";
import useToggle from "@/hooks/useToggle";
import { getAccountList, exportAccount, delAccount, getExportList } from "@/api/equipmentManagement/account.api.js";
import useCountries from "@/hooks/useCountries";
import { downloadZipFile } from '@/utils/index'
const { countriesList, getCountryName } = useCountries()
const [loading, _, setLoading] = useToggle();
import { useParamStore } from '@/store'
const route = useRoute();
const { setParams, getParams, removeFalsyValues } = useParamStore()
const name = route.fullPath
onMounted(() => {
  if(!!getParams(name)) {
    queryParams.value = getParams(name)
  }
  getList()
})


const paging = ref({
  size: 10,
  page: 1,
  total: 0,
});
const queryParams = ref({
  app: "TG",
  bundle: void undefined, // app类型
  devices: void undefined, // 设备名称
  sim: void undefined, // 号码类型
  country: void undefined, // 国家名称
  mobile: void undefined, // 手机号
  status: void undefined, // 状态
  exported: void undefined, // 是否导出
  times: void undefined,
});

const tableData = ref([]);

const getList = async () => {
  try {
    setLoading(true);
    const params = JSON.parse(JSON.stringify(queryParams.value));
    params.devices = params.devices ? params.devices.split(",") : []

    const { count, rows } = await getAccountList({ page: paging.value.page, size: paging.value.size, ...params });
    setLoading(false);
    
    paging.value.total = count;
    tableData.value = rows;
  } finally {
    setLoading(false);
  }
};

const handleSizeChange = (e) => {
  paging.value.size = e;
  getList()
};
const handleCurrentChange = (e) => {
  paging.value.page = e;
  getList()
};

const ids = ref([]);

const handleQuery = () => {
  paging.value.page = 1
  paging.value.size = 10
  setParams(queryParams.value, name)
  getList()
};

const queryFormRef = ref(null);
const handleResetQuery = () => {
  if (!queryFormRef.value) return
  queryFormRef.value.resetFields()
  queryParams.value.times = void undefined;
  handleQuery()
};
const handleSelectionChange = (e) => {
  ids.value = e.map((item) => item.id);
}

const handleClickBatch = (e, type, row) => {
  console.log(e, type, row);
  
  const commands = {
    export: () => handleExport(row),
    delete: () => handleDelete(row),
  }[`${e}`]

  return commands && commands();
};
const exportRowsRef = ref(null);
const handleExport = async (row) => {
  if(row.id) {
    const res = await exportAccount({ ids: [Number(row.id)], app: row.app, page: 1, size: 1000000 }, { responseType: 'blob' });
    const fileName = res.headers["content-disposition"] && res.headers["content-disposition"].split("=")[1];
    downloadZipFile(res.data, decodeURIComponent(fileName?.split("''")[1]) || 'default.tar')
    return
  }
  exportRowsRef.value?.handleOpen(queryParams.value)
};

const handleDelete = (row) => {
  if(!row.id && ids.value.length === 0) return ElMessage.warning('请选择要删除的记录');
  const tips = `确定删除${!row.id ? `${ids.value.length}条记录` : '这条记录'}?`;

  ElMessageBox.confirm(
    tips,
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      del()
    })


    const del = async() => {
      if(row.id) {
        const res =await delAccount({ ids: [Number(row.id)] })
        console.log(res);
        if(res) {
          ElMessage.success('删除成功');
          handleQuery();
        }
        return
      }

      const res =await delAccount({ ids: ids.value })
      if(res) {
        ElMessage.success('删除成功');
        handleQuery();
      }
    }
};

</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
